﻿using Newtonsoft.Json;
using Formatting = Newtonsoft.Json.Formatting;

namespace HyperplaneTech.CdrPlugin {

    /// <summary>
    /// JSON工具类
    /// </summary>
    public static class JsonUtil {

        /// <summary>
        /// 把对象转换为JSON字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>JSON字符串</returns>
        public static string ToJsonStr(this object o) {
            return ToJsonStr(o, NullValueHandling.Include, Formatting.None);
        }

        /// <summary>
        /// 把对象转换为JSON字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="nullValueHandling">如何忽略null值</param>
        /// <returns>JSON字符串</returns>
        public static string ToJsonStr(this object o, NullValueHandling nullValueHandling) {
            return ToJsonStr(o, nullValueHandling, Formatting.None);
        }

        /// <summary>
        /// 把对象转换为JSON字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="nullValueHandling">如何忽略null值</param>
        /// <param name="format">格式化类型</param>
        /// <returns>JSON字符串</returns>
        public static string ToJsonStr(this object o, NullValueHandling nullValueHandling, Formatting format) {
            JsonSerializerSettings setting = new JsonSerializerSettings();
            setting.NullValueHandling = nullValueHandling;
            setting.Formatting = format;
            return JsonConvert.SerializeObject(o, setting);
        }

        /// <summary>
        /// 把JSON字符串转换为对象
        /// </summary>
        /// <typeparam name="T">泛型对象</typeparam>
        /// <param name="json">JSON字符串</param>
        /// <returns>对象</returns>
        public static T FromJSON<T>(this string json) {
            return JsonConvert.DeserializeObject<T>(json);
        }

    }

}
